<script setup lang="ts">
import { ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { getJackWingListApi } from '@/api/jack'
import type { jackWingingItem } from '@/types/jack'
import { baseURL } from '@/utils/http'
import NoList from '@/components/NoList.vue'
import { useMemberStore } from '@/stores'
import { postUserScanCodeAPT } from '@/api/account'
import { getBusinessInfoByUseridAPI } from '@/api/business'
import { homePublickAPI } from '@/api/global'
import type { KpcodeJackpotEntity } from '@/types/global'
import { getXyjListApi, type KpcodeLuckyParamEntityItem } from '@/api/xyj'
import { isFull18Years } from '@/utils/utils'
import { postLoginWxMinAPI } from '@/api/account'
import { useRoleStore } from '../../stores/modules/role'
import { busListStore } from '../../stores/modules/bus'

const memberStore = useMemberStore()
// const isLogin = memberStore.profile
const isLogin = ref<boolean>(false)

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 获取个人信息
const getMemberProfileData = async () => {
  // 获取微信code
  const rescode = await wx.login()
  const { code } = rescode

  // 发起请求
  const loginrRes = await postLoginWxMinAPI(code)

  // const res = await getUserInfoByIdAPI(memberStore.profile.userId)
  memberStore.setProfile(loginrRes.data.appUser)
}

const openScanner = async () => {
  await getMemberProfileData()
  if (memberStore.profile.userId) {
    if (memberStore.profile.nameStatus == 2) {
      // 判断是否满18周岁
      const boristretor = memberStore.profile.idCard.slice(6, 14)
      if (isFull18Years(boristretor)) {
        // 调用uni.scanCode()函数进行扫一扫操作
        uni.scanCode({
          success(res) {
            postUserScanCode(res.result.split(',')[0])
          },
        })
      } else {
        uni.showToast({ icon: 'none', title: '根据国家相关法律要求，未满18周岁不得扫码！' })
      }
    } else {
      uni.showToast({ icon: 'none', title: '您还未实名认证，请认证后再进行抽奖' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/attes/attes' })
      }, 500)
    }
  } else {
    uni.showToast({ icon: 'none', title: '您还未登录，请登录后再进行抽奖' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/login/login' })
    }, 500)
  }
}

// 获取奖池信息
const indexJack = ref<KpcodeJackpotEntity>({
  jackpotPrice: '0',
  remainingPrice: '0',
})
const homePublick = async () => {
  const res = await homePublickAPI()
  indexJack.value = res.data
}

// 抽奖
const postUserScanCode = async (code: string) => {
  let obj = {
    scanCode: code,
    userId: memberStore.profile.userId,
  }
  const res = await postUserScanCodeAPT(obj)
  uni.showToast({ icon: 'none', title: res.msg })
}

// 获取 code 登录凭证
const loginProfile = {
  grant_type: 'mobile',
  mobile: 'MINI@',
  code: 'mobile',
}

onShow(() => {
  homePublick()
  getWingList()
  isLogin.value = memberStore.profile ? true : false
})

onLoad(() => {
  getXyjList()
})

// 获取获奖列表
const wingList = ref<jackWingingItem[]>([])
const pages = {
  size: 200
}
const getWingList = async () => {
  const res = await getJackWingListApi(pages)
  wingList.value = res.data.records
  if (wingList.value.length > 0) {
    wingList.value.map((item) => {
      item.areaNames = item.areaName.split(' ')
      if (item.appUser.avatar) {
        if (!item.appUser.avatar.includes('http')) {
          item.appUser.avatar = baseURL + item.appUser.avatar
        }
      }
    })
  }
}

// 跳转幸运奖页面
const xyjLisst = ref<KpcodeLuckyParamEntityItem[]>([])
const getXyjList = async () => {
  const res = await getXyjListApi()
  xyjLisst.value = res.data
}
const gotoXYJ = async () => {
  if (xyjLisst.value.length > 0) {
    uni.navigateTo({ url: '/pages/xinyun/xinyun' })
  } else {
    uni.showToast({ icon: 'none', title: '当前无幸运奖活动' })
  }
}

// 点击商务
const id = ref('')
const busStore = busListStore()
const roleStore = useRoleStore()
const clickBuiness = async () => {
  // 判断是否登陆
  if (memberStore.profile) {
    // // 判断是否有角色权限
    console.log(roleStore.roles)
    if (roleStore.roles) {
      if (roleStore.roles.includes('bus_user')) {
        id.value = memberStore.profile.userId
        const businessInfo = await getBusinessInfoByUseridAPI(id.value)
        if (businessInfo.data) {
          if (businessInfo.data.status == '1') {
            uni.showToast({ icon: 'none', title: '您已经提交入住信息，请耐心等待审核！' })
          }
          if (businessInfo.data.status == '2') {
            uni.redirectTo({ url: '/pages/business/business' })
          }
          if (businessInfo.data.status == '3') {
            uni.showToast({ icon: 'none', title: '您已经提交入住信息，审核不通过，请修改资料！' })
            setTimeout(() => {
              uni.navigateTo({ url: `/pages/join/join?id=${memberStore.profile.userId}` })
            }, 1000)
          }
        } else {
          uni.redirectTo({ url: '/pages/join/join' })
        }
      } else if (roleStore.roles.includes('agent_user')) {
        uni.redirectTo({ url: '/pages/indexAgent/indexAgent' })
      } else if (roleStore.roles.includes('bus_agent')) {
        uni.redirectTo({ url: '/pages/indexBusinessAgent/indexBusinessAgent' })
      } else if (roleStore.roles.includes('delivery_user')) {
        uni.redirectTo({ url: '/pages/carry/carry' })
      } else {
        uni.redirectTo({ url: '/pages/my/my' })
      }
    } else {
      uni.showToast({ icon: 'none', title: '您当前没有注册商户！' })
      setTimeout(() => {
        uni.navigateTo({ url: `/pages/join/join` })
      }, 1000)
    }
  } else {
    uni.redirectTo({ url: '/pages/login/login' })
  }
}
const activeIndex = ref(0)

const clickWallet = () => {
  // 判断是否登陆
  if (memberStore.profile) {
    uni.redirectTo({ url: '/pages/wallet/wallet' })
  } else {
    uni.redirectTo({ url: '/pages/login/login' })
  }
}
</script>

<template>
  <view
    class="index"
    :style="{
      paddingTop: safeAreaInsets?.top + 'px',
    }"
  >
    <view class="logo_index">
      <image src="@/static/images/cv-logo.png" />
    </view>
    <view class="main-nav">
      <view class="xyj">
        <navigator url="/pages/note/note" class="shuoming">
          <image src="@/static/images/cv-index-btn_shuoming.png" />
        </navigator>
        <!-- <view class="xyj_img" @tap="gotoXYJ">
          <image src="@/static/images/cv-index-btn_xy.png"/>
        </view> -->
      </view>
      <view class="jiangjin">
        <!-- <image class="jj_title" src="@/static/images/cv-index-cv.png"/> -->
        <text class="jine">奖池金额</text>
        <text class="money">
          {{ (Number(indexJack.jackpotPrice) + Number(indexJack.remainingPrice)).toFixed(2) }}
        </text>
      </view>
      <view class="right">
        <navigator url="/pages/newsList/newsList" class="link">
          <image src="@/static/images/cv-index-btn_tz.png" />
        </navigator>
        <view @tap="clickBuiness" class="link">
          <image src="@/static/images/cv-index-btn_sw.png" />
        </view>
        <view @tap="clickWallet" class="link">
          <image src="@/static/images/cv-index-btn_qb.png" />
        </view>
        <navigator url="/pages/my/my" class="link" v-if="isLogin">
          <image src="@/static/images/cv-index-btn_my.png" />
        </navigator>
        <navigator url="/pages/login/login" class="link" v-else>
          <image src="@/static/images/cv-index-btn_login.png" />
        </navigator>
      </view>
    </view>
    <view class="people_content">
      <view class="nav">
        <text :class="activeIndex == 0 ? 'active' : ''" @tap="activeIndex = 0">获奖名单</text>
        <text :class="activeIndex == 1 ? 'active' : ''" @tap="activeIndex = 1">获奖感言</text>
      </view>
      <view class="content content_0" v-if="activeIndex == 0">
        <view class="people_list">
          <template v-if="wingList.length > 0">
            <navigatorr to="" class="item" v-for="(item, index) in wingList" :key="item.id">
              <text class="no">{{ index + 1 }}.</text>
              <view class="wining_pic">
                <image :src="item.appUser.avatar" mode="aspectFill" v-if="item.appUser.avatar" />
                <image src="@/static/images/default-img.jpg" mode="aspectFill" v-else />
              </view>
              <text class="name">{{
                item.appUser.nickname || item.appUser.name || item.appUser.username
              }}</text>
              <text class="company">{{ item.jackPeriod }}</text>
              <text class="jackGrade">{{ item.jackGrade }}</text>
              <text class="win_type">{{ item.jackGrade == '幸运奖' ? '幸运奖' : '乐促奖' }}</text>
              <text class="area">{{ item.areaName ? item.areaNames[2] : '暂无' }}</text>
              <text class="jackEndTime">{{ item.openJackTime }}</text>
            </navigatorr>
          </template>

          <!-- <button class="loading-text" size="mini">查看更多</button> -->
          <no-list v-else />
        </view>
      </view>
      <view class="content content_1" v-if="activeIndex == 1">
        <view class="people_list">
          <template v-if="wingList.length > 0">
            <template v-for="item in wingList" :key="item.id">
              <navigatorr to="" class="win_item" v-if="item.winningSpeech">
                <view class="avatar">
                  <image :src="item.appUser.avatar" mode="aspectFill" v-if="item.appUser.avatar" />
                  <image src="@/static/images/default-img.jpg" mode="aspectFill" v-else />
                </view>
                <text class="name">{{
                  item.appUser.nickname || item.appUser.name || item.appUser.username
                }}</text>
                <text class="area">{{ item.areaName ? item.areaNames[2] : '暂无' }}</text>
                <text class="win_type">{{ item.jackGrade == '幸运奖' ? '幸运奖' : '乐促奖' }}</text>
                <text class="jackGrade">{{ item.jackGrade }}</text>
                <!-- <text>{{ item.createTime!.toString().substring(0, 11) }}</text> -->
                <!-- <text class="winningSpeech" v-if="item.winningSpeech">{{ item.winningSpeech }}</text> -->
                <text class="winningSpeech">{{ item.winningSpeech }}</text>
                <text class="jackPeriod">{{ item.jackPeriod }}</text>
                <text class="jackEndTime">{{ item.finishTime }}</text>
              </navigatorr>
            </template>
          </template>
          <!-- <button class="loading-text" size="mini">查看更多</button> -->
          <no-list v-else />
        </view>
      </view>
    </view>
  </view>
  <view class="scan" @tap="openScanner">
    <image class="scan_image" src="@/static/images/cv-sys.png" mode="aspectFill" />
  </view>
</template>

<style lang="scss">
page {
  height: 100vh;
  background-image: url(http://8.130.69.166/publick/cv-index-bg.jpg);
  background-color: rgb(253, 223, 182);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center -4vh;
  overflow: hidden;
}

.index {
  padding-top: 20px;
  height: 100%;
  position: relative;

  .logo_index {
    position: absolute;
    left: 40rpx;
    top: 100rpx;

    image {
      width: 213rpx;
      height: 81rpx;
    }
  }

  .main-nav {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    padding: 30rpx 30rpx 10rpx;
    //height: 49vh;
    overflow: hidden;
    margin-top: 2.3vh;

    .xyj {
      width: 200px;
      height: 200px;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      justify-content: flex-end;

      .xyj_img {
        width: 200rpx;
        height: 200rpx;

        image {
          width: 200rpx;
          height: 200rpx;
        }
      }

      .shuoming image {
        width: 114rpx;
        height: 114rpx;
        margin-left: 5px;
      }
    }

    .jiangjin {
      align-self: flex-start;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-top: 30rpx;
      padding-right: 40rpx;
      margin-left: -130px;

      .jj_title {
        width: 189rpx;
        height: 58rpx;
      }

      .jine {
        font-size: 48rpx;
        color: #333;
        font-weight: bold;
        margin: 40rpx 0 10rpx;
      }

      .money {
        font-size: 90rpx;
        color: #f74747;
        font-weight: bold;
        text-shadow: 0 2px 0 #ffd57a, 0 -2px 0 #ffd57a, 2px 0 0 #ffd57a, -2px 0 0 #ffd57a;
      }
    }

    .right {
      display: flex;
      flex-direction: column;
      align-items: flex-end;

      .link {
        margin-bottom: 20rpx;
      }

      .kaijiang {
        margin-bottom: 20rpx;
        display: inline-block;
        width: 140rpx;
        height: 60rpx;
        line-height: 56rpx;
        text-align: center;
        border-radius: 30rpx;
        background-color: rgba(0, 0, 0, 0.5);
        color: #fff;
        font-size: 24rpx;
      }

      image {
        width: 114rpx;
        height: 114rpx;
      }
    }
  }

  .people_content {
    width: 94vw;
    height: 51vh;
    margin: 0 auto;
    position: absolute;
    bottom: 10rpx;
    left: 3vw;
    .nav {
      height: 110rpx;
      border-radius: 50rpx 50rpx 0 0;
      position: absolute;
      top: 0;
      width: 100%;
      z-index: 1;
      background: linear-gradient(to bottom, #fe5a2b, #fd4120);
      display: flex;
      align-items: center;
      padding-bottom: 30rpx;
      border: 2rpx solid #ffe5a2;

      text {
        display: inline-block;
        width: 50%;
        text-align: center;
        height: 80rpx;
        line-height: 80rpx;
        border-radius: 50rpx 50rpx 0 0;
        color: #fff;
      }

      .active {
        background-color: #fff;
        color: #fd4120;
      }
    }

    .content {
      position: absolute;
      top: 80rpx;
      width: 100%;
      background-color: #fff;
      z-index: 2;
      border-radius: 28rpx;
      overflow-y: scroll;
      height: calc(100% - 80rpx);
      .people_list {
        padding: 20rpx 30rpx 90px;
      }

      .item {
        padding: 10rpx 0;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        align-items: center;
        font-size: 24rpx;
        line-height: 2em;
        border-bottom: 1px solid #efefef;
        padding-top: 10px;

        text {
          margin-right: 10px;
        }

        .no {
          width: 10px;
          color: #999;
          font-size: 20rpx;
          margin-right: 5px;
        }

        .area {
          width: 40px;
        }

        .jackGrade {
          margin-left: 20px;
        }

        .name {
          width: 40%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: initial;
          margin-left: 5px;
        }

        .company {
          margin-right: 0;
          width: calc(50% - 30px);
          text-align: right;
        }

        .type {
          width: 40px;
          margin-right: 0;
        }

        .wining_pic,
        .wining_pic image {
          width: 20px;
          height: 20px;
          border-radius: 10px;
        }

        .wining_info {
          flex: 1;
          width: 100%;
          height: 20px;
          overflow: hidden;
        }

        .jackEndTime {
          text-align: right;
          margin-right: 0;
        }
      }

      .win_item {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        font-size: 12px;
        align-items: center;
        border-bottom: 1px solid #efefef;
        padding-top: 10px;

        view,
        text {
          margin-bottom: 10px;
        }

        .avatar {
          width: 20px;
          height: 20px;

          image {
            width: 20px;
            height: 20px;
            border-radius: 10px;
          }
        }

        .name {
          margin: 0 0 10px;
          width: 100px;
          overflow: hidden;
        }

        .area {
          width: 50px;
        }

        .win_type {
          width: 50px;
        }

        .jackEndTime {
          width: 50%;
          text-align: right;
        }

        .jackGrade {
          width: 50px;
          text-align: right;
        }

        .jackPeriod {
          width: 50%;
        }

        .winningSpeech {
          width: 100%;
          text-align: justify;
        }
      }
    }

    .content_0 {
      border-radius: 0 28rpx 28rpx 28rpx;
    }

    .content_1 {
      border-radius: 28rpx 0 28rpx 28rpx;
    }

    .loading-text {
      width: 100%;
      margin-top: 10px;
    }
  }
}
</style>
